package com.appspot.yeswether.jdo;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.appspot.yeswether.KoreanDateUtil;
import com.appspot.yeswether.ScrapUtil;
import com.appspot.yeswether.Weather;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import javax.jdo.Query;

public class WeatherManager {
	private static final long HOUR3=60*1000*60*3;
	private  final Logger logg = Logger.getLogger(WeatherManager.class.getName()); 
	public void putWeather(Weather inweather) {
		changeWeatehrImage(inweather);
		PersistenceManager pm = PMF.get().getPersistenceManager(); 
		try{
			inweather.setScrapTime(System.currentTimeMillis());
			inweather.setKey(WeatherManager.createWeatherKey(inweather.getRegionCode(), inweather.getDateString()));
			pm.makePersistent(inweather);	
		}catch(Exception e){			
		}finally{
			pm.close();
		}
	}
	
	public Weather getWeather(String regionCode, String dateString){
		Weather weather= getWeather(WeatherManager.createWeatherKey(regionCode, dateString));		
		if(isTimeOver(weather, dateString)){
			try{
				ScrapUtil scrapUtil=new ScrapUtil();
				weather=scrapUtil.getWeaterFromWeb(regionCode);
				putWeather(weather);
			} catch(Exception e){
			}
		}		
		return weather;
	}
	
	private boolean isTimeOver(Weather weather, String dateString){
		String todayString=KoreanDateUtil.getDateString(0);
		if(!todayString.equals(dateString)){
			return false;
		}
		if(weather==null || weather.getScrapTime() ==0){
			return true;
		}
		long current=System.currentTimeMillis();
		if(current > weather.getScrapTime()+HOUR3 ){
			return true;
		}
		return false;
	}
	
	private void changeWeatehrImage(Weather weather){
		if(weather ==null) return;
		
		String img=weather.getMorningImg();
		weather.setMorningImg("/img/"+img.substring(img.lastIndexOf("/")+1, img.lastIndexOf("."))+".png");
		img=weather.getEveningImg();
		weather.setEveningImg("/img/"+img.substring(img.lastIndexOf("/")+1, img.lastIndexOf("."))+".png");
		
		img=weather.getTmorningImg();
		weather.setTmorningImg("/img/"+img.substring(img.lastIndexOf("/")+1, img.lastIndexOf("."))+".png");
		img=weather.getTeveningImg();
		weather.setTeveningImg("/img/"+img.substring(img.lastIndexOf("/")+1, img.lastIndexOf("."))+".png");
	}
	
	public Weather getWeather(Key key) {
		PersistenceManager pm = PMF.get().getPersistenceManager(); 
		Weather weather=null;
		try{
			weather = pm.getObjectById(Weather.class, key);	
		}catch(Exception e){
			logg.log(Level.ALL, "Error ... "+e.getMessage());
		}finally{
			pm.close();
		}
		return weather;
	}
	
	@SuppressWarnings("unchecked")
	public void deleteDumy(){
		PersistenceManager pm = PMF.get().getPersistenceManager(); 
		String yesterday=KoreanDateUtil.getDateString(-1);
		String sql="dateString<'"+yesterday+"'";
		Query query = pm.newQuery(Weather.class, sql);
		query.setRange(0, 1000);
		
		List<Weather> list;
		try{
			list=(List<Weather>)query.execute();
			if(list.size() >0){
				pm.deletePersistentAll(list);
			}
		}catch(Exception e){
			logg.warning(e.getMessage());
			e.printStackTrace();
		}finally{
			query.closeAll();
			pm.close();
		}		
	}
	
	public static Key createWeatherKey(String regionCode, String dateString){
		return KeyFactory.createKey(Weather.class.getSimpleName(), regionCode+dateString); 
	}

}
